#!/usr/bin/env python
# -*- coding:utf-8 -*-

# file:do_exam1.py
# author:王雯雯
# datetime:2024-12-7
# software: PyCharm
from flask import Flask, render_template, request, redirect, url_for
from flask_sqlalchemy import SQLAlchemy

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from datetime import datetime

app = Flask(__name__)

# 配置数据库连接（请根据实际情况修改用户名、密码和数据库名）
app.config['SQLALCHEMY_DATABASE_URI'] ='mysql+pymysql://root:12345678@localhost/todo_list'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

# 创建SQLAlchemy实例
db = SQLAlchemy(app)

# 定义Todo模型类
class Todo(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(255), nullable=False)
    due_time = db.Column(db.DateTime)
    status = db.Column(db.String(20), default='active')

# 创建数据库表（如果不存在）
with app.app_context():
    db.create_all()

# 首页路由，展示所有待办事项并处理筛选、搜索逻辑
@app.route('/', methods=['GET'])
def index():
    # 获取筛选条件（默认为'all'，显示所有）
    filter_status = request.args.get('status', 'all')
    # 获取搜索关键词（默认为空字符串）
    search_keyword = request.args.get('search', '')

    todos = Todo.query
    if filter_status!= 'all':
        todos = todos.filter(Todo.status == filter_status)
    if search_keyword:
        todos = todos.filter(Todo.title.like(f'%{search_keyword}%'))

    todos = todos.all()

    return render_template('index.html', todos=todos, filter_status=filter_status, search_keyword=search_keyword)

# 添加待办事项路由
@app.route('/add', methods=['POST'])
def add():
    title = request.form.get('title')
    due_time_str = request.form.get('due_time')
    due_time = datetime.strptime(due_time_str, '%Y-%m-%dT%H:%M') if due_time_str else None
    new_todo = Todo(title=title, due_time=due_time)
    db.session.add(new_todo)
    db.session.commit()
    return redirect(url_for('index'))

# 更新待办事项状态路由（比如标记为已完成或恢复为未完成等操作）
@app.route('/update_status/<int:todo_id>', methods=['POST'])
def update_status(todo_id):
    new_status = request.form.get('status')
    todo = Todo.query.get(todo_id)
    if todo:
        todo.status = new_status
        db.session.commit()
    return redirect(url_for('index'))

# 删除待办事项路由
@app.route('/delete/<int:todo_id>', methods=['GET'])
def delete(todo_id):
    todo = Todo.query.get(todo_id)
    if todo:
        db.session.delete(todo)
        db.session.commit()
    return redirect(url_for('index'))

if __name__ == '__main__':
    app.run(debug=True)